package com.gitee.paymentzk.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.util.concurrent.CountDownLatch;

/**
 * @ClassName ZookeeperConfig
 * @Description   分布式中心的配置  demo
 * @Author xiongchao
 * @Date 2021/1/7 9:23
 **/
@Slf4j
public class ZookeeperConfig implements Watcher {


    private static CountDownLatch count = new CountDownLatch(1);

    private static ZooKeeper zk = null;

    private static Stat state = new Stat();

    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected == watchedEvent.getState() && null == watchedEvent.getPath()){
            // zk 连接成功通知事件
            count.countDown();
        } else  if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            // zk 节点数据发生变化事件
            try {
                log.info("配置已修改，新值为：{}",new String(zk.getData(watchedEvent.getPath(),true,state)));
                System.out.println("配置已修改，新值为：" + new String(zk.getData(watchedEvent.getPath(),true,state)));
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) throws Exception {
        //配置数据存放位置路径
        String path = "/username";
        // 建立 zk连接 并注册监听器
        zk = new ZooKeeper("114.55.164.189:2181", 5000 , new ZookeeperConfig());
        //等待zk连接成功通知
        count.await();
        //获取path节点数据配置数据 ，并注册监听
        log.info("设置的数据为：{}",new String( zk.getData(path,true,state)));
        System.out.println(new String( zk.getData(path,true,state)));
        Thread.sleep(Integer.MAX_VALUE);

    }
}
